package com.gzc.just.play.last.war.common.net;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.jupiter.api.Test;

import java.nio.ByteOrder;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class ByteOrderTest {

    @Test
    public void testLittleEndianEncoding() {

        ByteBuf buffer = Unpooled.buffer();
        try {

            int testValue = 0x12345678;
            buffer.order(ByteOrder.LITTLE_ENDIAN).writeInt(testValue);

            assertEquals(0x78, buffer.getByte(0));
            assertEquals(0x56, buffer.getByte(1));
            assertEquals(0x34, buffer.getByte(2));
            assertEquals(0x12, buffer.getByte(3));

            buffer.readerIndex(0);

            int readValue = buffer.order(ByteOrder.LITTLE_ENDIAN).readInt();

            assertEquals(testValue, readValue);

            buffer.readerIndex(0);
            int bigEndianValue = buffer.order(ByteOrder.BIG_ENDIAN).readInt();

            assertEquals(0x78563412, bigEndianValue);

        } finally {
            buffer.release();
        }
    }

    @Test
    public void testByteOrderVerification() {

        ByteBuf buffer = Unpooled.buffer();
        try {

            int testValue = 0x12345678;
            buffer.order(ByteOrder.LITTLE_ENDIAN).writeInt(testValue);

            assertEquals(0x78, buffer.getByte(0));
            assertEquals(0x56, buffer.getByte(1));
            assertEquals(0x34, buffer.getByte(2));
            assertEquals(0x12, buffer.getByte(3));

            buffer.readerIndex(0);

            int readValue = buffer.order(ByteOrder.LITTLE_ENDIAN).readInt();

            assertEquals(testValue, readValue);

        } finally {
            buffer.release();
        }
    }
}
